﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Blog.Core;

namespace Blog.Controllers
{
    public class CommentsController : Controller
    {
        public ActionResult CommentsTree(int id)
        {
            Theme theme = ViewController.GetTheme(id);
            if (theme == null)
                return RedirectToAction("Index", "Home");

            ViewData["Theme"] = theme;
            ViewData["Messages"] = ViewController.GetMessagesTree(theme);
            return View();
        }

        public ActionResult Create(int themeId, int messageTreeId, int parentMessageId, string text)
        {
            if (text != null && !string.IsNullOrEmpty(text.Trim()))
            {
                Theme theme = ViewController.GetTheme(themeId);
                if (theme != null)
                {
                    Message m = new Message(theme);
                    m.MessageTreeId = messageTreeId;
                    m.ParentId = parentMessageId;
                    m.MessageText = text;
                    m.UserName = User != null && User.Identity != null ? User.Identity.Name : string.Empty;
                    m.Save();
                }
            }

            return RedirectToAction("CommentsTree/" + themeId);
        }

        public ActionResult Delete(int themeId, int messageId)
        {
            if (messageId > 0)
            {
                Theme theme = ViewController.GetTheme(themeId);
                if (theme != null)
                {
                    Message m = new Message(theme, messageId);
                    m.SetDeleted();
                    m.Save();
                }
            }

            return RedirectToAction("CommentsTree/" + themeId);
        }
    }
}
